<?php

namespace App\Common;

use App\Jobs\SyncSuning;
use App\Models\Product;
use App\Models\SuningApiLog;
use Illuminate\Support\Str;
use Mockery\Expectation;
use GuzzleHttp\Client;
use Cache;
class ThirdService
{

    protected static $mainUrl = 'http://101.125.0.54:10008/asapi-web/api/v1';

    //
    public static function getServices(){
        $cacheKey = 'huan_life_service_list_';
        $data = Cache::get($cacheKey);
        if(!empty($data)) return $data;
        $data = ThirdService::queryServiceRange();  // var_dump($data);
        $data = json_decode($data,true);
        Cache::put($cacheKey,$data,1);
        return $data;
    }



    public static function getServicesInfo($extdCmmdtyCtgry){
        $cacheKey = 'huan_life_service_info_';
        $data = Cache::get($cacheKey);
        if(!empty($data)) return $data;
        $data = ThirdService::queryAttributeInformation($extdCmmdtyCtgry);  // var_dump($data);
        $data = json_decode($data,true);
        Cache::put($cacheKey,$data,1);
        return $data;
    }

    /**
     * 3.4.2 商户查询商品关联的属性信息
     *
     */
    public static function queryAttributeInformation($extdCmmdtyCtgry='R0301003')
    {
        $method = 'query.attribute.information';
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id'),
            'extdCmmdtyCtgry' => $extdCmmdtyCtgry
        ];
        try {
            return static::GetSuningApiContent($method, $data);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * 3.4.3 直连商户订单下发ASMP
     * 商户将订单信息通过调用此接口发送给苏宁平台
     */
    function suningLbCreateorderCreate()
    {
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id'),
            'sourceOrderItemId' => Common::GetSerialNumber(), //商家系统订单号
            'consignee' => '高樊', //顾客姓名
            'mobPhoneNum' => '13311180918', //移动电话
            'phoneNum' => '', //固定电话
            'province' => '北京',
            'city' => '北京',
            'area' => '朝阳区',
            'street' => '劲松三区甲302',
            'address' => '华腾大厦2508', //详细地址
            'cityCode' => '010',
            'srvAreaCode' => '0100516',
            'cmmdtyQaType' => '1', //质保标识 0：保内；1：保外
            'extdCmmdtyBand' => '000281762',
            'extdCmmdtyCtgry' => 'R9010392', //苏宁商品编码
            'extdCommodityName' => '工程开荒保洁', //苏宁商品名称
            'brandCode' => '1762', //苏宁品牌编码
            'orderTime' => date("YmdHis"),
            'proName' => '08', //作业项目
            'saleDate' => '20201116',
            'saleQty' => '1', //服务数量
            'serviceTime' => date("YmdHis", strtotime('+2days')), //预约时间
            'propertyCode' => (object)[], //商品属性集合?
            'srvMemo' => '测试订单' //服务订单备注?
        ];
        $method = 'suning.lb.createorder.create';
        SyncSuning::dispatch($method, $data);
        return 0;
    }

    /**
     * 3.4.1 商户查询订购的商品和品牌信息
     * 通过帮客系统签订合同后，可通过接口查询合同中订购的商品和品牌信息
     */
    public static function queryServiceRange()
    {
        $method = 'query.service.range';
        $data = [
            'seqNo' => Common::GetSerialNumber(),
            'vendorCode' => config('app.suning.id')
        ];
        try {
            return static::GetSuningApiContent($method, $data);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        return 0;
    }

    /**
     * 对苏宁接口请求的封装
     *
     * @return Object
     */
    public static function GetSuningApiContent($method, array $data)
    {
        $client = new Client();
        $dataStr = json_encode($data);
        $sign = Common::SuningSign($method, $dataStr, config('app.suning.app_key'), config('app.suning.app_secret'));
        $fullUrl = Common::SuningUrl(static::$mainUrl, $method, config('app.suning.app_key'), $sign);
        $resp_status = 0;
        $resp_content = '';
        try {
            $response = $client->request('POST', $fullUrl, [
                'body' => $dataStr,
                'timeout' => 5
            ]);
            $resp_status = $response->getStatusCode();
            if ($resp_status == 200) {
                $resp_content = $response->getBody()->getContents();
            }

        } catch (Expectation $e) {
            throw $e;
        } finally {
            // 记录调用日志
            SuningApiLog::create([
                'from' => 'SuningTestCommand',
                'req_url' => static::$mainUrl,
                'req_method' => 'POST',
                'req_param' => json_encode([
                    'method' => $method,
                    'app_key' => config('app.suning.app_key'),
                    'sign' => $sign
                ]),
                'req_body' => $dataStr,
                'resp_status' => $resp_status,
                'resp_body' => $resp_content
            ]);
        }

        return $resp_content;
    }

}
